﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileClean
{
    internal class ScanDir
    {
        private string _path;
        private TreeView _treeView;
        private ListView _listView;
        //private TreeNodeCollection _nodes;
        public ScanDir(TreeView treeView,ListView listView, string path)
        {
            _path = path;
            _treeView = treeView;
            _listView = listView;
            //_treeView.Nodes.Clear();
            //DirectoryInfo directoryInfo = new DirectoryInfo(_path);
            //TreeNode rootNode = new TreeNode(directoryInfo.Name);
            //_nodes.Add(rootNode);
        }
        //public void Scan()
        //{
        //    ScanDirectory(_path, _nodes);
        //}
        //public TreeNodeCollection GetNodes()
        //{
        //    return _nodes;
        //}
        public void ScanDirectory(string dir, TreeNodeCollection nodes)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(dir);
            TreeNode directoryNode = new TreeNode(directoryInfo.Name);            
            AsyncNodeAdd(nodes, directoryNode);
            //nodes.Add(directoryNode);

            try
            {
                foreach (var directory in directoryInfo.GetDirectories())
                {
                    ScanDirectory(directory.FullName, directoryNode.Nodes);
                }

                foreach (var file in directoryInfo.GetFiles())
                {
                    TreeNode fileNode = new TreeNode(file.Name);
                    //rectoryNode.Nodes.Add(fileNode);
                    AsyncNodeAdd(directoryNode.Nodes, fileNode);
                }
            }
            catch (UnauthorizedAccessException ex)
            {                
                //AsyncNodeAdd(directoryNode.Nodes, new TreeNode("无法访问该目录"));
                //Console.WriteLine(ex.Message);
            }
        }
        private void AsyncNodeAdd(TreeNodeCollection nodes, TreeNode newNode)
        {
            _treeView.BeginInvoke(new Action(() =>
            {
                if (nodes.ContainsKey(newNode.Name))
                {
                    return;
                }else if (nodes.Contains(newNode))
                {
                    return;
                }
                else
                {
                    nodes.Add(newNode);
                }                   
            }));
        }
        private long GetFileSize(string filePath, Common.FileSizeUnit fileSizeUnit)
        {
            // 检查文件是否存在，并返回文件大小
            if (File.Exists(filePath))
            {
                FileInfo fileInfo = new FileInfo(filePath);
                switch (fileSizeUnit)
                {
                    case Common.FileSizeUnit.Byte:
                        return fileInfo.Length;
                    case Common.FileSizeUnit.KB:
                        return fileInfo.Length / 1024;
                    case Common.FileSizeUnit.MB:
                        return fileInfo.Length / 1024 / 1024;
                    case Common.FileSizeUnit.GB:
                        return fileInfo.Length / 1024 / 1024 / 1024;
                    default:
                        return fileInfo.Length;
                }                
            }

            return 0; // 如果文件不存在，则返回0
        }
        public void SortNodes(TreeNodeCollection nodes)
        {
            // 将 TreeNodeCollection 转换为 List<TreeNode> 以便排序
            var nodeList = new List<TreeNode>();

            foreach (TreeNode node in nodes)
            {
                nodeList.Add(node);
            }
            // 按照文件大小进行排序
            nodeList.Sort((x, y) =>
            {
                // 假设节点的 Tag 属性存储的是文件路径
                long sizeX = GetFileSize(x.FullPath, Common.FileSizeUnit.Byte);
                long sizeY = GetFileSize(y.FullPath, Common.FileSizeUnit.Byte);
                return sizeY.CompareTo(sizeX);
            });

            // 清空原有的节点并重新添加排序后的节点
            nodes.Clear();
            foreach (var node in nodeList)
            {
                nodes.Add(node);
            }
        }
        public void DeleteNode(TreeNode node)
        {
            if (node.Parent == null)
            {
                return;
            }
            node.Remove();
        }
        public void DeleteSelectedNodes(TreeNodeCollection nodes, string name)
        {
            TreeNode tnode = null;
            foreach (TreeNode node in nodes)
            {
                if (node.Text == name)
                {
                    tnode = node;
                    break;
                }
            }
            if (tnode == null)
            {
                return;
            }
            string path = tnode.FullPath;
            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }
            else if (File.Exists(path))
            {
                File.Delete(path);
            }
            // 删除指定名称的节点
            tnode.Remove();
        }
        public void DeleteNodes(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                node.Remove();
            }
        }   
        public void DeleteEmptyNodes(TreeNodeCollection nodes)
        {
            for (int i = nodes.Count - 1; i >= 0; i--)
            {
                if (nodes[i].Nodes.Count == 0 && nodes[i].Tag == null)
                {
                    nodes[i].Remove();
                }
            }
        }
        private void SetListViewHead(ListView listView)
        {
            ColumnHeader columnHeader = new ColumnHeader();
            columnHeader.Text = "文件名";
            columnHeader.Width = 200;
            listView.Columns.Add(columnHeader);

            columnHeader = new ColumnHeader();
            columnHeader.Text = "文件大小";
            columnHeader.Width = 200;
            listView.Columns.Add(columnHeader);
        }
        public void ShowNodes(TreeNodeCollection nodes,Common.FileSizeUnit fileSizeUnit)
        {
            _listView.Invoke(new Action(() =>
            {
                _listView.Items.Clear();
                //SetListViewHead(_listView);
                foreach (TreeNode node in nodes)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = node.Text;
                    item.SubItems.Add(GetFileSize(node.FullPath, fileSizeUnit).ToString());
                    _listView.Items.Add(item);
                }
            }));
        }
    }
}
